package com.szh.mysobproject.util;

import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {
    private static final String TAG = "HttpUtils";

    /**
     * 获取网络数据的函数
     *
     * @param path :网址
     * @return 返回或得到的json数据
     */
    public static String getJsonByNetwork(String path) {
        String json = "";
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        1创建网络地址对象
        try {
            URL url = new URL(path);
//            2.获取网络连接对象
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();  //开始连接
//            3.获取服务器返回的数据
            InputStream is = conn.getInputStream();
//            4.读取流当中的数据
            int hasRead = 0;
            byte[] buf = new byte[1024];
            while (true) {
                hasRead = is.read(buf);
                if (hasRead == -1) {
                    break;
                }
                baos.write(buf, 0, hasRead);
            }
            is.close();
            json = baos.toString();
        } catch (Exception e) {
            e.printStackTrace();
            Log.i("tag123", "getJsonByNetwork: 异常" + e.getMessage());
        }

        return json;
    }
}